import 'dart:io';

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

class DownloadUtil {
  static Future<File?> downloadFile(String fileUrl,
      {bool fromCache = false}) async {
    try {
      var dirPath = await getCacheFilePath();
      final filePath = '$dirPath${fileUrl.substring(fileUrl.lastIndexOf('/'))}';
      var file = File(filePath);
      if (fromCache) {
        if (file.existsSync()) {
          return file;
        }
      }

      var dio = Dio();
      var response = await dio.download(fileUrl, filePath);
      if (response.statusCode == 200) {
        return File(filePath);
      }
    } catch (error) {
      print('download error:$error');
      return null;
    }

    return null;
  }

  static Future<File?> downloadFileProgress(String fileUrl, {bool fromCache = false, void Function(int, int)? progressCallBack}) async {
    var dirPath = await getCacheFilePath();
    final filePath = '$dirPath${fileUrl.substring(fileUrl.lastIndexOf('/'))}';
    var file = File(filePath);
    if(fromCache){
      if (file.existsSync()) {
        return file;
      }
    }
    var dio = Dio();
    var response = await dio.download(
      fileUrl,
      filePath,
      onReceiveProgress: progressCallBack
    );
    if(response.statusCode == 200){
      return File(filePath);
    }
    return null;
  }

  static Future<String> getCacheFilePath() async {
    var fileDir = await getApplicationDocumentsDirectory();
    return fileDir.path;
  }
}
